package com.gopay.common.cipher.utils;

import com.gopay.common.util.Base64;
import com.gopay.common.util.FileUtil;
import com.gopay.common.util.security.RemainInfoProtectUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 *
 * 图片加解密
 * @author dongdh
 * @ImageSensitiveUtils
 * @2017/10/17 14:16  www.gopay.com.cn Inc.All rights reserved.
 */


public final class ImageSensitiveUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageSensitiveUtils.class);

    /**定义后缀**/
    public static final String SUFFIX = ".sec";

    /**
     *
     * @param srcFile  加密前的图片
     * @param isDeleteSrc 是否删除加密前的图片
     * @return
     */
    public static File encrypt(File srcFile, boolean isDeleteSrc) {

        if (srcFile == null || !FileUtil.isPicExt("." + FilenameUtils.getExtension(srcFile.getName()))) {
            LOGGER.error("收到待加密图片不存在或非图片文件");
            return srcFile;
        }

        long start = System.currentTimeMillis();
        LOGGER.info("收到需要加密的图片{}，isDeleteSrc={}", srcFile.getAbsoluteFile(), isDeleteSrc);

        try {
            byte[] bytes = FileUtils.readFileToByteArray(srcFile);
            //文件内容转成base64编码
            String img64 = Base64.encode(bytes, "utf-8");   //.encodeBase64String(bytes);

            //base64 进行加密
            String en_64 = SensitiveInfoUtils.smartEncryptWithCheck(img64);

            //新文件命名 1234567.jpg  -->  1234567.jpg.sec
            String fileName = srcFile.getAbsolutePath() + SUFFIX;

            LOGGER.info("新文件路径{}", fileName);

            //加密后的新文件
            File enFile = new File(fileName);

            FileUtils.writeStringToFile(enFile, en_64);

            if (isDeleteSrc) {
                LOGGER.info("删除原始图片" + srcFile.getAbsolutePath());
                //srcFile.deleteOnExit();  使用安全删除类
                RemainInfoProtectUtil.deleteFileInDiskSafely(srcFile);
            }
            long end = System.currentTimeMillis();
            LOGGER.info("加密文件耗时：{} ", end - start);
            return enFile;
        } catch (Exception e) {
            LOGGER.error("加密图片出错,返回原文件" , e);
            return srcFile;
        }
    }


    /**
     * 解密图片
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(File file) throws  Exception {

        try {
            long start = System.currentTimeMillis();

            if (file == null) {
                return null;
            }

            if (!file.exists()) {
                LOGGER.info("加密文件不存在  直接返回源文件");
                File srcFile = new File(file.getAbsolutePath().replace(SUFFIX, ""));
                if (srcFile != null && srcFile.exists()) {
                    //返回原图
                    return FileUtils.readFileToByteArray(srcFile);
                } else {
                    LOGGER.info("源文件也不存在 返回null");
                    return null;
                }
            } else if (!file.getName().endsWith(SUFFIX)) {
                //如果不是sec后缀  则返回原图字节
                return FileUtils.readFileToByteArray(file);
            }

            String en64 = FileUtils.readFileToString(file);
            LOGGER.info("从文件中获取base64 加密后的字符");
            String de64 = SensitiveInfoUtils.smartDecryptWithCheck(en64);
            LOGGER.info("解密从文件中取出来的base64字符串");

            byte[] decodeBase64 = Base64.decode(de64.getBytes("utf-8"));
            long end = System.currentTimeMillis();
            LOGGER.info("解密文件耗时：{} ", end - start);
            return decodeBase64;

        } catch (Exception e) {
            LOGGER.error("解密图片出错" , e);
            throw e;
        }

    }


    public static void main(String[] args) throws Exception {
        String file = "C:\\Users\\ddh02\\Desktop\\370523199001283919269995.png";
        String filen = "C:\\Users\\ddh02\\Desktop\\123123123.png";

        File f = new File(file);
        System.out.println(f.getAbsolutePath());
        System.out.println(f.getPath());
        System.out.println(f.getName());
        System.out.println(FilenameUtils.getBaseName(f.getName()));
        System.out.println(FilenameUtils.getExtension(f.getName()));
        System.out.println(FilenameUtils.getFullPath(f.getPath()));

        /*
        C:\Users\ddh02\Desktop\412928194407073132596443.jpg
        C:\Users\ddh02\Desktop\412928194407073132596443.jpg
        412928194407073132596443.jpg
        412928194407073132596443
        jpg
        C:\Users\ddh02\Desktop\
         */

        //File encrypt = ImageSensitiveUtils.encrypt(f, true);
       // System.out.println(encrypt.getAbsolutePath());


        byte[] bytes = ImageSensitiveUtils.decrypt(new File("C:\\Users\\ddh02\\Desktop\\370523199001283919269995.png.sec"));

        FileUtils.writeByteArrayToFile(new File(filen),  bytes);

    }

}
